package com.hskn.hss.module.weather;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hskn.hss.core.domain.AjaxResult;
import com.hskn.hss.utils.Tools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/hss/weather")
public class WeatherController {

    @PostMapping("getCityWeather")
    public static AjaxResult getCityWeather(HttpServletRequest request) {
        StringBuffer buffer = new StringBuffer();
        BufferedReader in = null;
        try {
            JSONObject jsonObject = JSON.parseObject(Tools.getBody(request));
            if((jsonObject!=null&&!jsonObject.containsKey("city"))||jsonObject==null){
               return AjaxResult.error("city不能为空");
            }
            String urlNameString = "http://wthrcdn.etouch.cn/weather_mini?city=";
            if(jsonObject.containsKey("city")){
                urlNameString=urlNameString+jsonObject.getString("city");
            }
            URL realUrl = new URL(urlNameString);

            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setConnectTimeout(3 * 1000);
            //设置请求头
            connection.setRequestProperty("Charset","UTF-8");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36");
            connection.setRequestProperty("Referer","XXXXXX");
            connection.setRequestProperty("Accept","application/json,text/plain,*/*");
            connection.setRequestProperty("Accept-Encoding", "gzip,deflate");

            connection.connect();

            Map<String, List<String>> map = connection.getHeaderFields();
            in = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return AjaxResult.success("查询成功",buffer.toString());
    }


}
